package com.chinaedu.oc.action.manageauthority;

import java.math.BigInteger;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chinaedu.oc.context.Common.Session;
import com.chinaedu.oc.dao.manageauthority.ManageAuthorityDao;
import com.chinaedu.oc.dao.managegroup.ManageGroupDao;
import com.chinaedu.oc.dao.membership.MemberShipDao;
import com.chinaedu.oc.entity.authority.ManageAuthority;
import com.chinaedu.oc.entity.authority.ManageAuthorityVO;
import com.chinaedu.oc.entity.managegroup.ManageGroup;
import com.chinaedu.oc.entity.manageuser.ManageUser;
import com.chinaedu.oc.util.common.IdCreater;
import com.chinaedu.oc.utils.ProcessResult;
import com.google.common.collect.Lists;

/**
 * @author lidan101
 * 权限列表页
 *  0： 菜单  1：按钮
 */
@Controller
@RequestMapping("/authority")
public class ManageAuthorityAction {
	
	@Resource
	private ManageAuthorityDao manageAuthorityDao;
	@Resource
	private MemberShipDao memberShipDao;
	@Resource
	private ManageGroupDao manageGroupDao;
	/**
	 * 权限管理页面列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public ProcessResult list(HttpServletRequest request, Model model) {
		ProcessResult pr= new ProcessResult();
		List<ManageAuthority> auths=null;
		Boolean status =false;
		try {
			auths = manageAuthorityDao.getAuthList();
			status=true;
		} catch (Exception e) {
			status=false;
		}
		pr.setData(auths);
		pr.setStatus(status);
		return pr;
	}
	
	
	/**
	 * 左侧菜单tree(只返回菜单)
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("leftMenuList")
	@ResponseBody
	public ProcessResult leftMenuList(HttpServletRequest request, Model model) {
		ProcessResult pr= new ProcessResult();
		//先取level为1的 菜单
		List<ManageAuthorityVO> firstAuths = manageAuthorityDao.getAuths("1","0");
		//遍历level为1的
		for(ManageAuthorityVO fauth:firstAuths){
			if(manageAuthorityDao.getAuthsByPid(fauth.getParentId(),"0")!=null){
				fauth.setChildren(manageAuthorityDao.getAuthsByPid(fauth.getId(),"0"));
			}
		}

		for(ManageAuthorityVO fauth:firstAuths){
			if(fauth.getChildren()!=null && fauth.getChildren().size()>0){
				for(ManageAuthorityVO sauth:fauth.getChildren()){
					if(manageAuthorityDao.getAuthsByPid(sauth.getParentId(),"0")!=null){
						sauth.setChildren(manageAuthorityDao.getAuthsByPid(sauth.getId(),"0"));
					}
				}
			}
			
		}
		//根据当前这个人的value值匹配一级菜单
		ManageUser manageUser = (ManageUser) request.getSession().getAttribute(Session.manageUserLogin.name());
		String groupId = manageUser.getGroupId();
		ManageGroup group = manageGroupDao.findGroupById(groupId);
		String authValue = group.getAuthValue();
		
		firstAuths = firstAuths.stream()
				.filter(a -> (a != null && ((new BigInteger(a.getAuthValue()).and(new BigInteger(authValue))).compareTo(new BigInteger(a.getAuthValue())) == 0)))
				.collect(Collectors.toList());
		
		List<ManageAuthorityVO> auths = Lists.newArrayList();
		//判断第一级的chileren的权限
		for(ManageAuthorityVO auth:firstAuths){
			if(auth.getChildren()!=null && auth.getChildren().size()>0){
				auths =auth.getChildren().stream()
				.filter(a -> (a != null && ((new BigInteger(a.getAuthValue()).and(new BigInteger(authValue))).compareTo(new BigInteger(a.getAuthValue())) == 0)))
				.collect(Collectors.toList());
				auth.setChildren(auths);
			}
		}
		
		List<ManageAuthorityVO> secondList = Lists.newArrayList();
		//判断第二级的children的权限
		for(ManageAuthorityVO auth:firstAuths){
			if(auth.getChildren()!=null && auth.getChildren().size()>0){
				for(ManageAuthorityVO m:auth.getChildren()){
					if(m.getChildren()!=null && m.getChildren().size()>0){
						secondList =m.getChildren().stream()
						.filter(a -> (a != null && ((new BigInteger(a.getAuthValue()).and(new BigInteger(authValue))).compareTo(new BigInteger(a.getAuthValue())) == 0)))
						.collect(Collectors.toList());
						m.setChildren(secondList);
					}
				}
			}
		}
		pr.setData(firstAuths);
		pr.setStatus(true);
		return pr;
	}
	
	
	/**
	 * 点击左侧菜单获取右侧按钮
	 * @param request
	 * @param model
	 * @param id 左侧菜单的id
	 * 0： 菜单  1：按钮
	 * @return 
	 */
	@RequestMapping("getBtns")
	@ResponseBody
	public ProcessResult getBtns(HttpServletRequest request, Model model,@RequestParam("id") String id) {
		ProcessResult pr= new ProcessResult();
		//session中获取用户信息
		ManageUser manageUser = (ManageUser) request.getSession().getAttribute(Session.manageUserLogin.name());
		//关系表中获取组id
		
		String groupId = memberShipDao.findGroupIdByUserId(Objects.nonNull(manageUser) ? manageUser.getUserId() : "0");
		//根据用户组id获取该角色的权限值
		String authvalue = manageGroupDao.findAuthValueByGroupId(groupId);
		List<ManageAuthority> selectedAuthorities = Lists.newArrayList();//当前用户拥有的权限
		List<ManageAuthority> authorities = Lists.newArrayList();
		authorities = manageAuthorityDao.getAuthsByPidAndType("1",id);// 获取权限表中所有的menuUrl(根据节点id和按钮类型)
		selectedAuthorities = authorities.stream()
							.filter(a -> (a != null && ((new BigInteger(a.getAuthValue()).and(new BigInteger(authvalue))).compareTo(new BigInteger(a.getAuthValue())) == 0)))
							.collect(Collectors.toList());
		pr.setData(selectedAuthorities);
		pr.setStatus(true);
		return pr;
	}
	
	
	/**
	 * 获取用户组页面  点击权限管理时 获取tree及回显数据
	 * @param request
	 * @param groupId   角色id
	 * @return
	 */
	@RequestMapping("getAuthorityTree")
	@ResponseBody
	public ProcessResult getAuthorityTree(HttpServletRequest request,@RequestParam("groupId")String groupId) {
		ProcessResult pr= new ProcessResult();
		List<ManageAuthority> authorities =Lists.newArrayList();
		if("".equals(groupId)||"undefined".equals(groupId)||groupId==null){
			authorities = manageAuthorityDao.getAuthList();//获取所有权限链接
		}else{
			//根据groupId获取权限值
			String authvalue = manageGroupDao.findAuthValueByGroupId(groupId);
			List<ManageAuthority> selectedAuthorities = Lists.newArrayList();//当前角色已勾选的权限
			authorities = manageAuthorityDao.getAuthList();//获取所有权限链接
			selectedAuthorities = authorities.stream()
					.filter(a -> (a != null && ((new BigInteger(a.getAuthValue()).and(new BigInteger(authvalue))).compareTo(new BigInteger(a.getAuthValue())) == 0)))
					.collect(Collectors.toList());
			selectedAuthorities.forEach(a->{
				a.setChecked(true);
			});
			//标记checked
			for(ManageAuthority m:authorities){
				for(ManageAuthority s:selectedAuthorities){
					if(m.getId().equals(s.getId())){
						m.setChecked(true);
					}
				}
			}
		}
		
		pr.setData(authorities);
		pr.setStatus(true);
		return pr;
	}
	
	
	/**
	 * 增加权限时  点击父权限 获取的列表（一个普通集合）
	 * @param request
	 * @return
	 */
	@RequestMapping("getParentTree")
	@ResponseBody
	public ProcessResult getParentTree(HttpServletRequest request) {
		ProcessResult pr= new ProcessResult();
		List<ManageAuthority> auths = manageAuthorityDao.getAuthList();
		pr.setData(auths);
		pr.setStatus(true);
		return pr;
	}
	
	
	/**
	 * 增加、编辑权限
	 * @param request
	 * @param auth
	 * @return
	 */
	@RequestMapping("saveAuthority")
	@ResponseBody
	public ProcessResult saveAuthority(HttpServletRequest request,
									@ModelAttribute ManageAuthority auth
									) {
		ProcessResult pr= new ProcessResult();
		if(null ==auth.getId() || "".equals(auth.getId())){
			//新建
			auth.setId(IdCreater.getId());
			auth.setChecked(false);//默认false
			String value = manageAuthorityDao.getMaxAuthvalue();
			value =new BigInteger(value).multiply(new BigInteger("2")).toString();
			auth.setAuthValue(value);
			manageAuthorityDao.saveAuth(auth);
		}else{
			//更新
			manageAuthorityDao.updateAuth(auth);
		}
		//新建或编辑时把authvalue值放到session中
		if(auth.getAuthValue()!=null){
			request.getSession().setAttribute(Session.authValueCommon.name(), auth.getAuthValue());
		}
		
		pr.setStatus(true);
		return pr;
	}
	
	/**
	 * 删除权限
	 * @param request
	 * @param auth
	 * @return
	 */
	@RequestMapping("delAuthority")
	@ResponseBody
	public ProcessResult delAuthority(HttpServletRequest request,
									@ModelAttribute ManageAuthority auth
									) {
		ProcessResult pr= new ProcessResult();
		if(null==auth ||auth.getId().equals("")){
			pr.setStatus(false);
			pr.setMsg("参数id为空");
			return pr;
		}
		manageAuthorityDao.delAuth(auth);
		pr.setStatus(true);
		return pr;
	}
	
	@RequestMapping("test")
	@ResponseBody
	public ProcessResult test(HttpServletRequest request,
									@ModelAttribute ManageAuthority auth
									) {
		ProcessResult pr= new ProcessResult();
		List<ManageAuthority> lists = manageAuthorityDao.getAuthList();
		String value = "1";
		for(ManageAuthority m:lists){
			m.setAuthValue(value);
			value =new BigInteger(value).multiply(new BigInteger("2")).toString();
			manageAuthorityDao.updateAuth(m);
		}
		pr.setStatus(true);
		return pr;
	}
	
	public static void main(String[] args) {
		BigInteger aa = new BigInteger("12111111111111111111111111111111");
		BigInteger bb =  aa.multiply(new BigInteger("2"));
		System.out.println(bb);
	}
}
